// 用于配置对应路由
let express = require('express')
let bulidquery = require('../api/bulid_query')
let router = express.Router()
router.use(express.json());
router.use(express.urlencoded({
    extended: true
}));

// //获取所有楼栋信息
router.get('/', function (req, res) {
    res.redirect('/bulids'); // 重定向
});
router.get('/bulids', (req, res) => {
    bulidquery.getall(function (rec) {
        res.json(rec).end();
    });
});

//获取指定name的楼栋信息 {通过id}
router.get('/bulids/:bulid_id', function (req, res) {
    var bulid_id = parseInt(req.params.bulid_id);
    bulidquery.get(bulid_id, function (rec) {
        res.json(rec).end();
    });
    console.log(bulid_id);
});

//使用POST方法添加楼栋信息
router.post('/bulids', function (req, res) {
    var reqbody = req.body;
    console.log(reqbody);
    var arr = [];
    //遍历JSON数据中所有的值
    for (var key in reqbody) {
        arr.push(reqbody[key]);
    }
    bulidquery.add([reqbody.bulid_name, reqbody.head_name, reqbody.sex, reqbody.phone], function (rec) {
        res.json(rec).end();
    });
});

//使用PUT方法修改楼层信息 TODO
router.put('/bulids/:bulid_id', function (req, res) {
    var bulid_id = parseInt(req.params.bulid_id);
    var reqbody = req.body;
    console.log(reqbody);
    //先判断ID是否有效，再执行修改操作
    bulidquery.get(bulid_id, function (rec) {
        if (rec.length == 0) {
            res.status(404).json({
                msg: '指定ID的楼栋不存在！'
            });
        } else {
            var arr1 = [];
            var arr2 = [];
            for (var key in reqbody) {
                arr1.push(key); //键
                arr2.push(reqbody[key]); //值
            }
            bulidquery.update([reqbody.head_name, reqbody.sex, reqbody.phone, bulid_id], function (rec) {
                res.json(rec).end();
            });
        }
    });
});

//使用DELETE方法删除图书信息
router.delete('/bulids/:id', function (req, res) {
    var bulid_id = parseInt(req.params.id);
    // var reqbody = req.body;
    //先判断ID是否有效，再执行删除操作
    bulidquery.get(bulid_id, function (rec) {
        if (rec.length == 0) {
            res.status(404).json({
                msg: '指定ID的楼层不存在！'
            });
        } else {
            bulidquery.del(bulid_id, function (p) {
                res.json(rec).end();
            });
        }
    });
});
module.exports = router